<template>
  <div>
    <!-- <div class="i-layout-page-header">
      <PageHeader class="product_tabs" title="车票订单" hidden-breadcrumb>
      </PageHeader>
    </div> -->
    <cards-data :cardLists="cardLists" v-if="cardLists.length >= 0"></cards-data>
    <Card :bordered="false" dis-hover>
      <Form ref="orderData"  :model="orderData"  :label-width="labelWidth"  :label-position="labelPosition"  class="tabform"  @submit.native.prevent >
        <Row :gutter="24" type="flex" justify="end">
          <Col span="24" class="ivu-text-left">
            <FormItem label="订单状态：">
              <RadioGroup  v-model="orderData.status" type="button"  @on-change="userSearchs"   >
                <Radio v-for="(item, index) in orderStatusList" :label="item.val" :key="index">{{ item.label }}</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="24">
            <Col span="8"  class="ivu-text-left">
              <FormItem label="所属城市：" label-for="pid">
                <Select v-model="orderData.city_id"  @on-change="selectCity" placeholder="请选择所属城市">
                  <Option v-for="item in cityList" :value="item.city_id" :key="item.id">{{ item.city_name }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="8"  class="ivu-text-left">
              <FormItem label="所属公司：" label-for="pid">
                <Select v-model="orderData.company_id"   placeholder="请选择所属城市">
                  <Option v-for="item in companyList" :value="item.id" :key="item.id">{{ item.company_name }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="8"  class="ivu-text-left">
              <FormItem label="线路名称："  prop="line_id" :label-width="100">
                <Select
                  placeholder="输入关键词选择线路"
                  v-model="orderData.line_id"
                  filterable
                  :remote-method="remoteMethodartFrom" 
                  :loading="loading1">
                  <Option v-for="(item, index) in options2" :value="item.line_id" :key="index">{{item.line_sn+item.line_name}}</Option>
                </Select>
              </FormItem>
            </Col>
          </Col>
          
          <Col span="24" class="ivu-text-left">
            <!-- <Col span="8">
              <FormItem label="创建时间：">
                <DatePicker
                  :editable="false"
                  @on-change="onchangeTime"
                  :value="orderData.add_time"
                  format="yyyy/MM/dd HH:mm:ss"
                  type="datetimerange"
                  placement="bottom-start"
                  placeholder="自定义时间"
                  class="mr20"
                  :options="options"
                ></DatePicker>
              </FormItem>
            </Col> -->
            <Col span="8">
              <FormItem label="出行日期：">
                <DatePicker
                  @on-change="onchangeUseTime"
                  :value="orderData.date"
                  format="yyyy/MM/dd"
                  type="daterange"
                  placement="bottom-start"
                  placeholder="自定义时间"
                  class="mr20"
                ></DatePicker>
              </FormItem>
            </Col>
            <Col span="8" >
              <FormItem label="搜索：" prop="real_name" label-for="real_name">
                <Input v-model="orderData.real_name"  search  enter-button placeholder="请输入" element-id="name" @on-search="orderSearch"  >
                  <Select v-model="orderData.field_key" slot="prepend" style="width: 60px" >
                    <Option value="all">全部</Option>
                    <Option value="order_id">订单号</Option>
                    <Option value="uid">用户ID</Option>
                    <Option value="real_name">用户姓名</Option>
                    <Option value="user_phone">用户电话</Option>
                    <Option value="order_name">订单名称</Option>
                  </Select>
                </Input>
              </FormItem>
            </Col>
          </Col>
        </Row>    

      </Form>
      <div class="Button">
        <Tooltip content="导出订单" >
          <Button
          @click="exports"
           size="small"
            class="export"
            icon="ios-share-outline"
            >导出</Button
          >
        </Tooltip>
      </div>
      <Table
        ref="table"
        :columns="columns"
        :data="tableList"
        class="ivu-mt"
        :loading="loading"
        highlight-row
        no-data-text="暂无数据"
        no-filtered-data-text="暂无筛选结果"
      >
      <template slot-scope="{ row, index }"  slot="refund_price">
        <span>{{row.refund_price?(row.refund_price/100):'--'}}</span>
      </template>
        <template slot-scope="{ row, index }" slot="action">
          <a @click="lookOrderBus(row)">查看车票</a>  
          <Divider v-if="row.paid!=0" type="vertical" />
          <a  v-if="row.paid!=0" @click="refundShowClick(row)">立即退款</a>  
        </template>
      </Table>
      <div class="acea-row row-right page">
        <Page
          :total="total"
          :current="orderData.page"
          show-elevator
          show-total
          @on-change="pageChange"
          :page-size="orderData.limit"
        />
      </div>
      <!--  查看乘客 -->
      <Modal title="车票信息" width="55%" v-model="orderBusVisible" :mask-closable="false" footer-hide>
        <Table
        ref="table"
        :columns="columns2"
        :data="orderBusList"
        class="ivu-mt"
        highlight-row
        no-data-text="暂无数据"
        no-filtered-data-text="暂无筛选结果"
        >
        <template slot-scope="{ row,index }" slot="passenger_info">
           <template v-if="row.passenger_list&&row.passenger_list.length">
              <div v-for="(item,index) in row.passenger_list" :key="index">
                <span>{{ item.name }}-</span><span>{{ item.id_card }}-</span><span>{{ item.phone }}-</span><span>{{ item.type==1?'成人票':'儿童票' }}</span>
              </div>
            </template>
            <div v-else>
              无乘客信息
            </div>        
        </template>
        </Table>
      </Modal>
      <!-- 查看乘客 -->
      <!-- 立即退款 -->
      <Modal
        v-model="refundShow"
        title="退款处理"
        ok-text="提交退款"
        @on-ok="sumRefund"
        @on-cancel="cancelRefund">
        <Form ref="refundForm" :model="refundForm" :label-width="120" class="demo-ruleForm">
          <FormItem label="订单号:">
            <Input v-model="refundForm.order_id" disabled  />
          </FormItem>
          <FormItem label="退款金额:">
            <InputNumber  :min="0" :max="Maxprice" v-model="refundForm.refund_price"></InputNumber>
          </FormItem>
          <FormItem label="退款理由:">
            <Input v-model="refundForm.refund_reason_wap_explain" type="textarea" :autosize="true" placeholder="请输入退款理由" />
          </FormItem>
        </Form>
      </Modal>
      <!-- 立即退款 -->
    </Card>
      
  </div>
</template>

<script>
  import { mapState, mapMutations } from "vuex";
  import expandRow from "./tableExpand.vue";
  import cardsData from '../../../components/cards/cards';
  import {adminInfoApi} from "@/api/setting"
  import {orderBusLst,exportOrderBusListApi,orderBusRefund } from "@/api/order"
  import { searchLineApi} from "@/api/line";
  import exportExcel from "@/utils/newToExcel.js";

  export default {
    name: 'list',
    components: {
        cardsData,
        expandRow
    },
    computed: {
      ...mapState("admin/layout", ["isMobile"]),
      labelWidth() {
      return this.isMobile ? undefined : 80;
      },
      labelPosition() {
      return this.isMobile ? "top" : "right";
      },
      today() {
      const end = new Date();
      const start = new Date();
      var datetimeStart =
          start.getFullYear() +
          "/" +
          (start.getMonth() + 1) +
          "/" +
          start.getDate();
      var datetimeEnd =
          end.getFullYear() + "/" + (end.getMonth() + 1) + "/" + end.getDate();
      return [datetimeStart, datetimeEnd];
      },
    },
    data () {
      return {
        Maxprice:0,
        loading1:false,
        options2:[],
        cityList: [],
        companyList:[],
        cardLists:[],
        tableList:[],
        loading: false,
        refundShow:false,
        orderBusList:[],
        refundForm:{
          order_id:'',
          refund_price:0,
          refund_reason_wap_explain:''
        },
          // 搜索条件
        orderData: {
          page:1,
          limit:25,
          status: "",
          company_id:"",
          city_id:"",
          line_id:"",
          add_time: "",
          real_name: "",
          field_key: "all",
          pay_type: "",
          date:'',
        },
        columns: [
          {
          type: "expand",
          width: 30,
          render: (h, params) => {
            return h(expandRow, {
              props: {
                row: params.row,
              },
            });
          },
        },
          {
            title: "订单号",
            key: "order_id",
            width: 160,
          },
          {
            title: "手机号",
            key: "user_phone",
            width: 110,
          },
          {
            title: "订单名",
            key: "order_name",
            minWidth: 180,
          },
          {
            title: "出行日期",
            key: "date_all",
            minWidth: 140,
          }, 
          {
            title: "订单状态",
            key: "order_status_desc",
            minWidth: 70,
          },
          {
            title: "票数",
            key: "passenger_num",
            minWidth: 70,
          },
          {
            title: "订单总金额",
            key: "total_price",
            minWidth: 100,
          },
          {
            title: "实付金额",
            key: "pay_price",
            minWidth: 100,
          },
          {
            title: "优惠金额",
            key: "coupon_price",
            minWidth: 100,
          },
          {
            title: "抵扣金额",
            key: "deduction_price",
            minWidth: 70,
          },
          {
            title: "退款金额",
            key: "refund_price",
            minWidth: 70,
          },
          {
            title: "操作",
            slot: "action",
            fixed: "right",
            minWidth: 120,
          },
        ],
        columns2:[
    
          {
            title: "手机号",
            key: "user_phone",
            width: 110,
          },
          {
            title: "出行日期",
            key: "date_desc",
            width: 120,
          },
          {
            title: "上车点",
            key: "on_stop_name",
            width: 120,
          },
          {
            title: "下车点",
            key: "off_stop_name",
            width: 120,
          },
          {
            title: "乘车人数",
            key: "passenger_num",
            width: 80,
          },
          {
            title: "乘车人信息",
            slot: "passenger_info",
            width: 260,
          },
          
          
          
        ],
        timeVal: [],
        total: 0,
        orderBusVisible:false,
        orderStatusList: [
          { label: "全部", val: "" },
          { label: "待支付", val: '0' },
          { label: "待出行", val: '1' },
          { label: "待评价", val: '2' },
          { label: "已退款", val: '-2' },
          { label: "已删除", val: '-4' },
        ],
        options: {
          shortcuts: [
            {
              text: "今天",
              value() {
                const end = new Date();
                const start = new Date();
                start.setTime(
                  new Date(
                    new Date().getFullYear(),
                    new Date().getMonth(),
                    new Date().getDate()
                  )
                );
                return [start, end];
              },
            },
            {
              text: "昨天",
              value() {
                const end = new Date();
                const start = new Date();
                start.setTime(
                  start.setTime(
                    new Date(
                      new Date().getFullYear(),
                      new Date().getMonth(),
                      new Date().getDate() - 1
                    )
                  )
                );
                end.setTime(
                  end.setTime(
                    new Date(
                      new Date().getFullYear(),
                      new Date().getMonth(),
                      new Date().getDate() - 1
                    )
                  )
                );
                return [start, end];
              },
            },
            {
              text: "最近7天",
              value() {
                const end = new Date();
                const start = new Date();
                start.setTime(
                  start.setTime(
                    new Date(
                      new Date().getFullYear(),
                      new Date().getMonth(),
                      new Date().getDate() - 6
                    )
                  )
                );
                return [start, end];
              },
            },
            {
              text: "最近30天",
              value() {
                const end = new Date();
                const start = new Date();
                start.setTime(
                  start.setTime(
                    new Date(
                      new Date().getFullYear(),
                      new Date().getMonth(),
                      new Date().getDate() - 29
                    )
                  )
                );
                return [start, end];
              },
            },
            {
              text: "本月",
              value() {
                const end = new Date();
                const start = new Date();
                start.setTime(
                  start.setTime(
                    new Date(new Date().getFullYear(), new Date().getMonth(), 1)
                  )
                );
                return [start, end];
              },
            },
            {
              text: "本年",
              value() {
                const end = new Date();
                const start = new Date();
                start.setTime(
                  start.setTime(new Date(new Date().getFullYear(), 0, 1))
                );
                return [start, end];
              },
            },
          ],
        },
      }
    },
    created () {
  
    },
    beforeDestroy () {
      
    },
    mounted () {
        // 今天的时间
    var day2 = new Date()
    day2.setTime(day2.getTime())
    var s2 = day2.getFullYear() + '/' + (day2.getMonth() + 1) + '/' + day2.getDate()
    this.orderData.date = [s2, s2]
        this.getAdminInfo()
    },
    methods: {
        // h获取管理员信息
      getAdminInfo(){
        this.loading = true;
        adminInfoApi().then((res) => {
          this.cityList = res.data.admin_roles_info
           this.loading = false;
          if(res.status==200){
             this.getList();
          }
        }).catch((error) => {
          console.log(error)
          this.$Message.error(error.msg||'错误请求')
        });
      },
       // 订单号搜索
      orderSearch() {
        // this.getOrderNum(num);
        // this.getfieldKey(this.orderData.field_key);
        // this.$emit("getList", 1);
        this.getList()
      },
      remoteMethodartFrom(query){
      this.options2 = []
      if (query !== '') {
        this.loading1 = true
        var that = this
         searchLineApi({line_name:query}).then(res => {
          this.loading1 = false
          res = res.data.list
          that.options2 = res
        }).catch(error => {
          console.log(error)
        })
      } else {
        this.options2 = []
      }
    },
        // 订单列表
      getList(res) {
      // this.page.pageNum = res === 1 ? 1 : this.page.pageNum;
      this.loading = true;

        orderBusLst(this.orderData).then(async (res) => {
          this.loading = false;
          let data = res.data;
          // this.orderList = data.data;
          // this.cardLists = data.stat
          this.tableList = data.data
          this.total = data.count;
        }).catch((res) => {
          this.loading = false;
            this.$Message.error(res.msg);
        });
      },
      userSearchs(type){
        this.orderData.status = type
        this.getList()
      },
      pageChange(status) {
        this.orderData.page = status;
        this.getList();
        this.$refs.table.clearCurrentRow();
      },

      // 提交退款
      sumRefund(){
        if(this.refundForm.refund_price<=0) {
          this.$Message.error('退款不能小于等于0')
        } else{
          orderBusRefund(this.refundForm).then(async (res) => {            
            this.getList();
            this.refundShow = false
            this.$Message.success(res.msg);      
        }).catch((res) => {
          this.loading = false;
            this.$Message.error(res.msg);
        });
        }
        //TODO
      },

          // 数据导出；
    async exports() {
      let [th, filekey, data, fileName] = [[], [], [], ""];
      let formValidate = this.orderData;
      this.$Spin.show();
      let lebData = await this.getExcelData(formValidate);
      this.$Spin.hide();
      if (!fileName) fileName = lebData.filename;
      if (!filekey.length) {
        filekey = lebData.filekey;
      }
      if (!th.length) th = lebData.header;
      if (lebData.export.length) {
        data = data.concat(lebData.export);
      }
     exportExcel(th, filekey, fileName, data);
    },
    getExcelData(excelData) {
      return new Promise((resolve, reject) => {
        exportOrderBusListApi(excelData).then((res) => {
          return resolve(res.data);
        });
      });
    },


      lookOrderBus(items){
        this.orderBusList = [items]
        this.orderBusVisible = true
      },
      // 退款
      refundShowClick(item){
        var price = 0
        if(item.total_price-item.refund_price<=0) {
          price = 0
        } else {
         price = item.total_price-item.refund_price
        }
        this.Maxprice = price
        this.refundForm = {
          order_id:item.order_id,
          refund_price: price,
          refund_reason_wap_explain:''
        }
        this.refundShow = true
      },
      cancelRefund(){
        this.refundForm = {
          order_id:'',
          refund_price:'',
          refund_reason_wap_explain:''
        }
      },
            // 选择城市触发

      selectCity(id) {
      var city = {}
      this.cityList.forEach(function(item) {
          if (item.city_id === id) {
          city = item
          }
      })
      var that = this
      if (!city.company_ids) {
          that.$Message.error('该城市下没有公司,请前往维护管理添加公司！')
          return
      }
      that.companyList = city.company_list
      },
      // 具体日期
    onchangeTime(e) {
     
     this.orderData.add_time = e[0] ? e.join("-") : "";

    },
    onchangeUseTime(e){
      this.orderData.date =  e;;
    }
        
    }
  }
</script>
<style scoped lang="stylus">
    .product_tabs >>> .ivu-tabs-bar
      margin-bottom 0px !important
    .product_tabs >>> .ivu-page-header-content
      margin-bottom 0px !important
    .product_tabs >>> .ivu-page-header-breadcrumb
        margin-bottom 0px !important
.tabform {
  margin-bottom: 10px;
}    
</style>
